package com.ruoyi.web.util;

import com.ruoyi.core.entity.TokenInfo;
import com.ruoyi.core.util.JsonUtil;
import com.ruoyi.web.exception.TokenException;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {

    /**
     * 有效期为 60 * 60 *1000  一个小时
     */
    public static final Long JWT_TTL = 60 * 60 * 1000L;
    /**
     * 设置秘钥 明文(elane.cn)使用sm4加密(sm4秘钥随机uuid)
     */
    public static final String JWT_KEY = "RDkwRDVCMTFBRjFCQUQ0MA==";
    /**
     * 签名算法
     */
    private static final SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    /**
     * 使用HS256签名
     *
     * @param claims
     * @return
     */
    private static String createToken(Map<String, Object> claims, Long ttlMillis) {
        try {
            long nowMillis = System.currentTimeMillis();
            Date now = new Date(nowMillis);
            if (ttlMillis == null) {
                ttlMillis = JwtUtil.JWT_TTL;
            }
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            JwtBuilder builder = Jwts.builder()
                    .setClaims(claims)
                    //签发者
                    .setIssuer("雾都码农")
                    //签发时间
                    .setIssuedAt(now)
                    //使用HS256对称加密算法签名, 第二个参数为秘钥
                    .signWith(signatureAlgorithm, generalKey())
                    //设置过期时间
                    .setExpiration(expDate);
            return builder.compact();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException("token创建失败");
        }
    }

    /**
     * 无效期token
     *
     * @param claims
     * @return
     */
    private static String createToken(Map<String, Object> claims) {
        return createToken(claims, null);
    }

    /**
     * 创建token
     */
    public static String createToken(TokenInfo tokenInfo) {
        Map<String, Object> claims = new HashMap<>(2);
        claims.put("userId", tokenInfo.getUserId());
        claims.put("userName", tokenInfo.getUserName());
        claims.put("tokenInfo", tokenInfo);
        return createToken(claims);
    }

    /**
     * 生成加密后的秘钥 secretKey
     *
     * @return
     */
    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析
     *
     * @param token token
     * @return
     * @throws Exception
     */
    public static Claims parseToken(String token) {
        try {
            SecretKey secretKey = generalKey();
            return Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("令牌已过期");
        } catch (UnsupportedJwtException | IllegalArgumentException e) {
            throw new RuntimeException("令牌不合法");
        } catch (MalformedJwtException | SignatureException e) {
            throw new RuntimeException("令牌签名错误");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 获取用户名
     *
     * @param token token
     * @return
     */
    public static TokenInfo getTokenInfo(String token) {
        Claims claims = parseToken(token);
        return JsonUtil.toBean(claims.get("tokenInfo"), TokenInfo.class);
    }

    /**
     * 刷新token
     *
     * @param token
     * @return
     */
    public static String refreshToken(String token) {
        try {
            final Claims claims = parseToken(token);
            return createToken(claims, null);
        } catch (Exception e) {
            throw new TokenException("刷下token异常：" + e.getMessage());
        }
    }

    public static void checkToken(String token) {
        try {
            Claims claims = parseToken(token);
        } catch (Exception e) {
            throw new TokenException("无效token");
        }
    }

}
